package com.qianclass.talklive.app.activity;

import android.app.Activity;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.StrictMode;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.lzy.okgo.OkGo;
import com.qianclass.talklive.app.utils.FileLogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import io.agora.rtc.RtcEngineEx;

/**
 * Created by apple on 15/9/15.
 */
public class TalkApplication extends Application {

	private RtcEngineEx rtcEngine;

	private MessageHandler messageHandler;

	private SharedPreferences user;
	private SharedPreferences username;
	private SharedPreferences userpwd;
	private SharedPreferences autologin;

	private SharedPreferences.Editor userEditor;
	private SharedPreferences.Editor usernameEditor;
	private SharedPreferences.Editor userpwdEditor;
	private SharedPreferences.Editor autologinEditor;

	private final static String EXTRA_USER = "user";
	private final static String USER_NAME = "username";
	private final static String USER_PWD = "userpwd";
	private final static String EXTRA_LOGIN = "login";
	private final static String ISFIRST = "isfirst";
	private final static String ISAUTOLOGIN = "isautologin";
	private final static String LOG_NAME = "name";
	private final static String USERID = "userid";

	private static String MECHANISM_ID = "";
	private static Map<String,Activity> destoryMap = new HashMap<>();

	@Override
	public void onCreate() {

		super.onCreate();
		// --------------------------------------------------------------------
		// 创建默认的ImageLoader配置参数
//		DisplayImageOptions option = new DisplayImageOptions.Builder()
//		 .showImageOnLoading(R.drawable.ic_launcher) // 设置图片在下载期间显示的图片
//		 .showImageForEmptyUri(R.drawable.ic_launcher)// 设置图片Uri为空或是错误的时候显示的图片
//		 .showImageOnFail(R.drawable.ic_launcher) // 设置图片加载/解码过程中错误时候显示的图片
//				.cacheInMemory(true)// 设置下载的图片是否缓存在内存中
//				.cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
//				.cacheOnDisk(true).build();// 构建完成
//
//		ImageLoader.getInstance().init(
//				ImageLoaderConfiguration.createDefault(this));
		EventBus.getDefault().register(this);

	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onStartInitEvent(String msg) {

		if (msg.equals("app_init")) {
			init();
			EventBus.getDefault().post("init_finished");
		}
	}

	public void init() {
		/**
		 * 针对7.0以上手机版本更新
		 */
		StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
		StrictMode.setVmPolicy(builder.build());
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			builder.detectFileUriExposure();
		}

		FileLogUtils.init(this);

		CrashHandler.newsIntance().init(this);
		OkGo.init(this);
		Fresco.initialize(this);

		messageHandler = new MessageHandler();

		user = this.getSharedPreferences(EXTRA_USER, MODE_PRIVATE);
		username = this.getSharedPreferences(USER_NAME, MODE_PRIVATE);
		userpwd = this.getSharedPreferences(USER_PWD, MODE_PRIVATE);
		autologin = this.getSharedPreferences(EXTRA_LOGIN, MODE_PRIVATE);

		userEditor = user.edit();
		usernameEditor = username.edit();
		userpwdEditor = userpwd.edit();
		autologinEditor=autologin.edit();
		if (rtcEngine != null) {
			rtcEngine.enableLastmileTest();
		}
	}

	// ----------------------------------------------------------------------------------------------
	/**
	 * 添加到销毁队列
	 *
	 * @param activity 要销毁的activity
	 */

	public static void addDestoryActivity(Activity activity, String activityName) {
		destoryMap.put(activityName,activity);
	}
	/**
	 *销毁指定Activity
	 */
	public static void destoryActivity(String activityName) {
		Set<String> keySet=destoryMap.keySet();
		for (String key:keySet){
			destoryMap.get(key).finish();
		}
	}
	// create RtcEngine
	public void setRtcEngine(String vendorKey) {

		if (rtcEngine != null) {
			rtcEngine = null;
		}
		try {
			rtcEngine = (RtcEngineEx) RtcEngineEx.create(getApplicationContext(),
                    vendorKey, messageHandler);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// get RtcEngine
	public RtcEngineEx getRtcEngine() {

		return rtcEngine;
	}

	public void isAutoLogin(boolean b){
		autologinEditor.putBoolean(ISAUTOLOGIN,b);
		autologinEditor.apply();
	}
	public Boolean getAutoLogin(){
		return autologin.getBoolean(ISAUTOLOGIN,false);
	}

	public void setIsFirst(boolean b){
		userEditor.putBoolean(ISFIRST, b);
		userEditor.apply();
	}

	public Boolean getIsFirst(){
		return user.getBoolean(ISFIRST,true);
	}

	public void setUserAccount(String userAccount){
		usernameEditor.putString(USER_NAME,userAccount);
		usernameEditor.apply();
	}
	public String getUSerAccount(){
		return username.getString(USER_NAME,"");
	}
	public void setUserPwd(String userAccount){
		userpwdEditor.putString(USER_PWD,userAccount);
		userpwdEditor.apply();
	}
	public String getUserPwd(){
		return userpwd.getString(USER_PWD,"");
	}

	public void setUserID(int userid){
		userEditor.putInt(USERID,userid);
		userEditor.apply();
	}
	public int getUserID(){
		return user.getInt(USERID,0);
	}
	public void setErrorLogFileName(String name){
		userEditor.putString(LOG_NAME,name);
		userEditor.apply();
	}

	@Override
	public AssetManager getAssets() {
		return super.getAssets();
	}

	public void setEngineEventHandlerActivity(BaseEngineEventHandlerActivity engineEventHandlerActivity){
        messageHandler.setActivity(engineEventHandlerActivity);
    }

	public static void setMechanismID(String mechanismID){
		MECHANISM_ID = mechanismID;
	}

	public static String getMechanismId(){
		return MECHANISM_ID;
	}
}